package com.sxhuayuan.parking.compenent.shiro.realm;

import com.sxhuayuan.parking.compenent.domain.Setting.CaptchaType;
import com.sxhuayuan.parking.compenent.shiro.AccountType;
import com.sxhuayuan.parking.compenent.shiro.AuthenticationToken;
import com.sxhuayuan.parking.compenent.shiro.Principal;
import com.sxhuayuan.parking.entity.Agent;
import com.sxhuayuan.parking.service.AgentService;
import com.sxhuayuan.parking.service.CaptchaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 代理登录验证
 */
@Component("agentAuthenticationRealm")
public class AgentAuthenticationRealm extends AuthorizingRealm {

	Logger log = LoggerFactory.getLogger(AgentAuthenticationRealm.class);

	@Resource(name = "captchaServiceImpl")
	private CaptchaService captchaService;
	@Resource(name = "agentServiceImpl")
	private AgentService agentService;

	@Override
	public String getName() {
		return "agent";
	}

	@Override
	public boolean supports(org.apache.shiro.authc.AuthenticationToken token) {
		return token != null && token instanceof AuthenticationToken;
	}

	/**
	 * 获取认证信息(登录验证)
	 * 
	 * @param token
	 *            令牌
	 * @return 认证信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken token) {

		AuthenticationToken authenticationToken = (AuthenticationToken) token;

		String username = authenticationToken.getUsername();
		if (StringUtils.isEmpty(username) || authenticationToken.getPassword() == null) {
			throw new IncorrectCredentialsException();
		}
		String password = new String(authenticationToken.getPassword());
		String captchaId = authenticationToken.getCaptchaId();
		String captcha = authenticationToken.getCaptcha();
		String ip = authenticationToken.getHost();

		// 验证码
		if (!captchaService.isValid(CaptchaType.agentLogin, captchaId, captcha)) {
			throw new UnsupportedTokenException();
		}

		Agent agent = agentService.findByUsername(username);
		if (agent == null) {
			throw new UnknownAccountException();
		}
		if (!agent.getIsEnabled()) {
			throw new DisabledAccountException();
		}

		if (!agent.getPassword().equals(password)) {
			throw new IncorrectCredentialsException();
		}
		// 更新登录信息
		agent.setLoginIp(ip);
		agent.setLoginDate(new Date());
		try {
			agentService.update(agent);
		} catch (Exception e) {
			log.error("", e);
		}
		return new SimpleAuthenticationInfo(new Principal(AccountType.agent, agent.getId(), username), password, getName());
	}

	/**
	 * 获取授权信息(访问权限)
	 * 
	 * @param principals
	 *            principals
	 * @return 授权信息
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Principal principal = (Principal) principals.fromRealm(getName()).iterator().next();
		if (principal != null) {
			List<String> authorities = agentService.findAuthorities(principal.getId());
			if (authorities != null) {
				SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
				authorizationInfo.addStringPermissions(authorities);
				return authorizationInfo;
			}
		}
		return null;
	}
}
